<template>
  <div class="statistics-page">
    <div class="page-header">
      <h1>肺部CT数据统计分析</h1>
      <div class="header-actions">
        <a-space>
          <a-select v-model="selectedPatient" placeholder="选择患者" style="width: 200px">
            <a-option v-for="patient in patients" :key="patient.id" :value="patient.id">
              {{ patient.name }} ({{ patient.id }})
            </a-option>
          </a-select>
          <a-select v-model="chartType" placeholder="图表类型" style="width: 150px">
            <a-option value="trend">病情趋势</a-option>
            <a-option value="comparison">时期对比</a-option>
            <a-option value="distribution">病灶分布</a-option>
          </a-select>
          <a-button type="primary">
            <template #icon><icon-download /></template>
            导出报告
          </a-button>
        </a-space>
      </div>
    </div>
    
    <div class="page-content">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="patient-info-card">
            <template #title>患者信息</template>
            <div v-if="currentPatient" class="patient-info">
              <a-descriptions :data="patientInfoData" layout="vertical" size="small" />
              
              <a-divider style="margin: 16px 0" />
              
              <div class="examination-history">
                <div class="section-title">检查记录</div>
                <a-timeline>
                  <a-timeline-item 
                    v-for="exam in currentPatient.examinations" 
                    :key="exam.date"
                    :dot-color="getTimelineDotColor(exam.status)"
                  >
                    <div class="timeline-content">
                      <div class="timeline-title">{{ exam.date }}</div>
                      <div class="timeline-desc">{{ exam.description }}</div>
                      <a-tag :color="getStatusColor(exam.status)">{{ exam.status }}</a-tag>
                    </div>
                  </a-timeline-item>
                </a-timeline>
              </div>
            </div>
            <a-empty v-else description="请选择一位患者" />
          </a-card>
        </a-col>
        
        <a-col :span="18">
          <a-card class="chart-card">
            <template #title>
              <span>{{ chartTitle }}</span>
              <a-tooltip content="刷新数据">
                <a-button type="text" shape="circle" class="refresh-btn">
                  <template #icon><icon-refresh /></template>
                </a-button>
              </a-tooltip>
            </template>
            <div class="chart-container" ref="chartContainer"></div>
          </a-card>
          
          <a-card class="data-card" style="margin-top: 16px">
            <template #title>数据分析</template>
            <a-tabs>
              <a-tab-pane key="summary" title="汇总分析">
                <div v-if="currentPatient" class="analysis-content">
                  <a-descriptions :data="analysisData" layout="vertical" />
                  
                  <div class="key-metrics">
                    <div class="metric-item">
                      <div class="metric-value improvement">↓ 23.5%</div>
                      <div class="metric-label">病灶体积减少</div>
                    </div>
                    <div class="metric-item">
                      <div class="metric-value">4次</div>
                      <div class="metric-label">检查次数</div>
                    </div>
                    <div class="metric-item">
                      <div class="metric-value improvement">↑ 15.2%</div>
                      <div class="metric-label">肺功能改善</div>
                    </div>
                  </div>
                </div>
                <a-empty v-else description="请选择一位患者" />
              </a-tab-pane>
              <a-tab-pane key="details" title="详细数据">
                <a-table :columns="tableColumns" :data="tableData" :pagination="false" />
              </a-tab-pane>
            </a-tabs>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue';
import { IconDownload, IconRefresh } from '@arco-design/web-vue/es/icon';
import * as echarts from 'echarts';

// 患者数据
const patients = [
  {
    id: 'P001',
    name: '张三',
    age: 45,
    gender: '男',
    department: '呼吸内科',
    doctor: '王医生',
    diagnosis: '肺部感染',
    examinations: [
      { date: '2025-08-15', description: '首次CT检查', status: '异常' },
      { date: '2025-09-20', description: '复查CT', status: '好转' },
      { date: '2025-10-25', description: '复查CT', status: '好转' },
      { date: '2025-12-05', description: '复查CT', status: '正常' }
    ],
    data: {
      dates: ['2025-08-15', '2025-09-20', '2025-10-25', '2025-12-05'],
      lesionVolume: [124, 95, 45, 12],
      normalTissue: [4196, 4225, 4275, 4308],
      leftLung: [2150, 2160, 2160, 2160],
      rightLung: [2170, 2160, 2160, 2160],
      distribution: {
        upperLeft: 35,
        upperRight: 45,
        middleLeft: 15,
        middleRight: 20,
        lowerLeft: 5,
        lowerRight: 4
      }
    }
  },
  {
    id: 'P002',
    name: '李四',
    age: 52,
    gender: '男',
    department: '呼吸内科',
    doctor: '张医生',
    diagnosis: '肺结节',
    examinations: [
      { date: '2025-07-10', description: '首次CT检查', status: '异常' },
      { date: '2025-08-25', description: '复查CT', status: '异常' },
      { date: '2025-10-15', description: '复查CT', status: '好转' },
      { date: '2025-12-20', description: '复查CT', status: '好转' }
    ],
    data: {
      dates: ['2025-07-10', '2025-08-25', '2025-10-15', '2025-12-20'],
      lesionVolume: [35, 38, 20, 15],
      normalTissue: [4285, 4282, 4300, 4305],
      leftLung: [2150, 2150, 2150, 2150],
      rightLung: [2170, 2170, 2170, 2170],
      distribution: {
        upperLeft: 10,
        upperRight: 60,
        middleLeft: 5,
        middleRight: 15,
        lowerLeft: 5,
        lowerRight: 5
      }
    }
  },
  {
    id: 'P003',
    name: '王五',
    age: 38,
    gender: '女',
    department: '呼吸内科',
    doctor: '李医生',
    diagnosis: '肺炎',
    examinations: [
      { date: '2025-09-05', description: '首次CT检查', status: '异常' },
      { date: '2025-10-10', description: '复查CT', status: '好转' },
      { date: '2025-11-15', description: '复查CT', status: '好转' }
    ],
    data: {
      dates: ['2025-09-05', '2025-10-10', '2025-11-15'],
      lesionVolume: [150, 80, 30],
      normalTissue: [4170, 4240, 4290],
      leftLung: [2150, 2150, 2150],
      rightLung: [2170, 2170, 2170],
      distribution: {
        upperLeft: 25,
        upperRight: 30,
        middleLeft: 20,
        middleRight: 15,
        lowerLeft: 5,
        lowerRight: 5
      }
    }
  }
];

const selectedPatient = ref('P001');
const chartType = ref('trend');
let chart: echarts.ECharts | null = null;

// 当前选中的患者
const currentPatient = computed(() => {
  return patients.find(p => p.id === selectedPatient.value);
});

// 患者信息数据
const patientInfoData = computed(() => {
  if (!currentPatient.value) return [];
  
  return [
    { label: '姓名', value: currentPatient.value.name },
    { label: 'ID', value: currentPatient.value.id },
    { label: '年龄', value: `${currentPatient.value.age}岁` },
    { label: '性别', value: currentPatient.value.gender },
    { label: '科室', value: currentPatient.value.department },
    { label: '主治医生', value: currentPatient.value.doctor },
    { label: '诊断', value: currentPatient.value.diagnosis }
  ];
});

// 分析数据
const analysisData = computed(() => {
  if (!currentPatient.value) return [];
  
  const data = currentPatient.value.data;
  const firstExam = data.lesionVolume[0];
  const lastExam = data.lesionVolume[data.lesionVolume.length - 1];
  const changePercent = ((firstExam - lastExam) / firstExam * 100).toFixed(1);
  
  return [
    { label: '首次检查病灶体积', value: `${firstExam} cm³` },
    { label: '最近检查病灶体积', value: `${lastExam} cm³` },
    { label: '病灶体积变化', value: `减少 ${changePercent}%` },
    { label: '检查次数', value: data.dates.length },
    { label: '治疗周期', value: `${Math.round((new Date(data.dates[data.dates.length - 1]).getTime() - new Date(data.dates[0]).getTime()) / (1000 * 60 * 60 * 24))} 天` }
  ];
});

// 表格列
const tableColumns = [
  { title: '检查日期', dataIndex: 'date' },
  { title: '病灶体积 (cm³)', dataIndex: 'lesionVolume' },
  { title: '正常组织体积 (cm³)', dataIndex: 'normalTissue' },
  { title: '左肺体积 (cm³)', dataIndex: 'leftLung' },
  { title: '右肺体积 (cm³)', dataIndex: 'rightLung' },
  { title: '病灶占比 (%)', dataIndex: 'percentage' }
];

// 表格数据
const tableData = computed(() => {
  if (!currentPatient.value) return [];
  
  const data = currentPatient.value.data;
  return data.dates.map((date, index) => {
    const total = data.leftLung[index] + data.rightLung[index];
    return {
      date,
      lesionVolume: data.lesionVolume[index],
      normalTissue: data.normalTissue[index],
      leftLung: data.leftLung[index],
      rightLung: data.rightLung[index],
      percentage: ((data.lesionVolume[index] / total) * 100).toFixed(2)
    };
  });
});

// 图表标题
const chartTitle = computed(() => {
  switch (chartType.value) {
    case 'trend':
      return '病灶体积变化趋势';
    case 'comparison':
      return '不同时期数据对比';
    case 'distribution':
      return '病灶分布情况';
    default:
      return '数据分析';
  }
});

// 获取状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case '正常':
      return 'green';
    case '好转':
      return 'blue';
    case '异常':
      return 'red';
    default:
      return 'gray';
  }
};

// 获取时间线点的颜色
const getTimelineDotColor = (status: string) => {
  switch (status) {
    case '正常':
      return 'green';
    case '好转':
      return 'blue';
    case '异常':
      return 'red';
    default:
      return 'gray';
  }
};

// 初始化图表
const initChart = () => {
  setTimeout(() => {
    const chartContainer = document.querySelector('.chart-container') as HTMLElement;
    if (chartContainer) {
      // 如果已有图表实例，先销毁
      if (chart) {
        chart.dispose();
      }
      
      chart = echarts.init(chartContainer);
      updateChart();
    }
  }, 100);
};

// 更新图表
const updateChart = () => {
  if (!currentPatient.value) return;
  
  // 如果图表不存在，初始化图表
  if (!chart) {
    const chartContainer = document.querySelector('.chart-container') as HTMLElement;
    if (chartContainer) {
      chart = echarts.init(chartContainer);
    } else {
      return;
    }
  }
  
  // 清除旧的图表配置
  chart.clear();
  
  const data = currentPatient.value.data;
  
  switch (chartType.value) {
    case 'trend':
      chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['病灶体积', '正常组织体积']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.dates
        },
        yAxis: [
          {
            type: 'value',
            name: '病灶体积 (cm³)',
            position: 'left'
          },
          {
            type: 'value',
            name: '正常组织体积 (cm³)',
            position: 'right',
            offset: 80
          }
        ],
        series: [
          {
            name: '病灶体积',
            type: 'line',
            data: data.lesionVolume,
            itemStyle: {
              color: '#F53F3F'
            },
            lineStyle: {
              width: 3
            }
          },
          {
            name: '正常组织体积',
            type: 'line',
            yAxisIndex: 1,
            data: data.normalTissue,
            itemStyle: {
              color: '#165DFF'
            },
            lineStyle: {
              width: 3
            }
          }
        ]
      });
      break;
      
    case 'comparison':
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['左肺', '右肺', '病灶']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.dates
        },
        yAxis: {
          type: 'value',
          name: '体积 (cm³)'
        },
        series: [
          {
            name: '左肺',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: data.leftLung,
            itemStyle: {
              color: '#37D4CF'
            }
          },
          {
            name: '右肺',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: data.rightLung,
            itemStyle: {
              color: '#168CFF'
            }
          },
          {
            name: '病灶',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: data.lesionVolume,
            itemStyle: {
              color: '#FF7D00'
            }
          }
        ]
      });
      break;
      
    case 'distribution':
      chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '病灶分布',
            type: 'pie',
            radius: '70%',
            data: [
              { value: data.distribution.upperLeft, name: '左肺上部' },
              { value: data.distribution.upperRight, name: '右肺上部' },
              { value: data.distribution.middleLeft, name: '左肺中部' },
              { value: data.distribution.middleRight, name: '右肺中部' },
              { value: data.distribution.lowerLeft, name: '左肺下部' },
              { value: data.distribution.lowerRight, name: '右肺下部' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
      break;
  }
};

// 监听患者和图表类型变化
watch([selectedPatient, chartType], () => {
  // 延迟执行，确保DOM已更新
  setTimeout(() => {
    updateChart();
  }, 50);
});

// 挂载时初始化图表
onMounted(() => {
  initChart();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

// 添加resize处理函数和图表清理函数
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 在组件卸载前清理图表实例和事件监听
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.statistics-page {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-fill-2);
}

.page-header {
  padding: var(--spacing-md) var(--spacing-xl);
  background-color: var(--color-bg-2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

h1 {
  font-size: 20px;
  margin: 0;
  color: var(--color-text-1);
  font-weight: 600;
  letter-spacing: 0.5px;
  white-space: nowrap;
}

.page-content {
  flex: 1;
  padding: var(--spacing-lg);
  overflow: auto;
}

.patient-info-card, .chart-card, .data-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.chart-container {
  height: 400px;
  width: 100%;
  position: relative;
  overflow: hidden;
}

.examination-history {
  margin-top: var(--spacing-md);
}

.section-title {
  font-weight: 600;
  margin-bottom: var(--spacing-sm);
  color: var(--color-text-1);
}

.timeline-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.timeline-title {
  font-weight: 500;
}

.timeline-desc {
  color: var(--color-text-3);
  font-size: 13px;
}

.refresh-btn {
  margin-left: var(--spacing-md);
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.key-metrics {
  display: flex;
  justify-content: space-between;
  margin-top: var(--spacing-md);
}

.metric-item {
  text-align: center;
  padding: var(--spacing-md);
  background-color: var(--color-fill-2);
  border-radius: var(--radius-md);
  flex: 1;
  margin: 0 var(--spacing-sm);
}

.metric-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: var(--spacing-xs);
}

.metric-label {
  color: var(--color-text-3);
  font-size: 14px;
}

.improvement {
  color: #00B42A;
}

.deterioration {
  color: #F53F3F;
}
</style> 